package com.tsystems.skilltest;

import java.util.List;
import java.util.Properties;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.xml.bind.JAXBException;

import org.apache.activemq.ActiveMQConnectionFactory;

public class TransactionReceiver
{
    private static Properties           properties   = PropertiesUtils.getProperties("skilltest.properties");
    private TransactionListXMLConverter xmlConverter = new TransactionListXMLConverter();

    private MessageConsumer             consumer;
    private Connection                  connection;

    public void init() throws JMSException
    {
        String url = properties.getProperty("jms.broker.url");
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
        connection = connectionFactory.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        String queue = properties.getProperty("jms.broker.queue");
        Destination destination = session.createQueue(queue);
        consumer = session.createConsumer(destination);
    }

    public Transaction receive() throws JMSException, JAXBException
    {
        Message message = consumer.receive();

        if (!(message instanceof TextMessage))
        {
            throw new JMSException("unexpected data was received");
        }

        TextMessage textMessage = (TextMessage) message;
        TransactionList transactionList = xmlConverter.unmarshal(textMessage.getText());
        List<Transaction> transactions = transactionList.getTransactions();

        if (transactions.size() != 1)
        {
            throw new JMSException("one transaction expected: ectually " + transactions.size());
        }
        return transactions.get(0);
    }

    public void close() throws JMSException {
        connection.close();
    }
}
